package com.hmall.order.Listener;

import com.hmall.common.client.ItemClient;
import com.hmall.common.client.OrderClient;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.Order;
import com.hmall.common.pojo.OrderDetail;
import com.hmall.order.constants.MqConstants;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Component
@RequiredArgsConstructor
@Slf4j
public class MqListener {

    private final OrderClient orderClient;

    private final ItemClient itemClient;

    //死信监听
    @RabbitListener(queues = MqConstants.ITEM_DEAD_QUEUE)
    @GlobalTransactional
    public void deadListener(String orderId) {
        Long id = Long.valueOf(orderId);
        //根据id查询订单-feign
        Order order = orderClient.queryOrderById(id);
        if (order != null && order.getStatus() == 1) {
            //根据id查询订单详细信息,获取商品信息-feign
            OrderDetail orderDetail = orderClient.queryOrderDetailById(id);
            Item itemQuery = itemClient.rowInfo(orderDetail.getItemId());
            Item itemUndo = new Item();
            itemUndo.setId(orderDetail.getItemId());
            int soldUndo = itemQuery.getSold() - orderDetail.getNum();
            int stockUndo = itemQuery.getStock() + orderDetail.getNum();
            itemUndo.setSold(soldUndo);
            itemUndo.setStock(stockUndo);
            //恢复商品的库存-feign
            itemClient.update(itemUndo);
            //更新订单状态
            order.setStatus(5);
            orderClient.update(order);
            //删除物流订单
            orderClient.deleteByOrderId(id);
        }

    }
}
